package com.coocaa.ops.admin.v1.buttonmanage.service;

import com.coocaa.ops.admin.base.properties.SystemProperties;
import com.coocaa.ops.admin.v1.audit.AuditUtil;
import com.coocaa.ops.admin.v1.auth.sys.constant.ButtonAccessEnums;
import com.coocaa.ops.admin.v1.auth.sys.constant.MenuTokenConstants;
import com.coocaa.ops.admin.v1.auth.sys.service.impl.SysAuthorizeServiceImpl;
import com.coocaa.ops.admin.v1.buttonmanage.converter.ButtonManageConverter;
import com.coocaa.ops.admin.v1.buttonmanage.model.ButtonManageModel;
import com.coocaa.ops.admin.v1.panel.biz.impl.PanelInfoBizImpl;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.base.util.ResourceStatusValidator;
import com.coocaa.ops.common.core.biz.audit.entity.AuditTaskInfoEntity;
import com.coocaa.ops.common.core.biz.auth.entity.SysRunEntity;
import com.coocaa.ops.common.core.biz.auth.entity.SysUserEntity;
import com.coocaa.ops.common.core.biz.panel.constant.PanelTypeConstants;
import com.coocaa.ops.common.core.biz.panel.entity.PanelInfoEntity;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.exception.BusinessException;
import com.coocaa.ops.common.tool.json.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2018/3/20.
 * @description: 审核等按钮 服务实现
 */
@Service
public class ButtonManageServiceImpl implements IButtonManageService {
    @Autowired
    private SysAuthorizeServiceImpl sysAuthorizeService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private PanelInfoBizImpl panelInfoBiz;

    /**
     * 获取审核详情相关操作按钮
     *
     * @param model
     * @param userEntity
     * @return
     */
    @Override
    public List<SysRunEntity> getAuditDetailButton(ButtonManageModel model, SysUserEntity userEntity) {
        List<SysRunEntity> sysRuns;
        AuditTaskInfoEntity taskInfo = AuditUtil.getTaskByIdAndVersionAndType(model.getResourceId(), model.getVersion(), model.getType());
        //当前所有按钮权限
        sysRuns = getCurrentAllSysRuns(model.getMenuElId(), userEntity);
        //要保留的按钮权限
        List<SysRunEntity> retainButtons = getRetainSysRunsForPanelButton(model, userEntity, taskInfo);
        //取交集
        ButtonManageConverter.removeButton(sysRuns, retainButtons);
        return sysRuns;
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    /**
     * 获取当前所有的按钮权限-PannelButton
     *
     * @param menuElId
     * @param userEntity
     * @return
     */
    private List<SysRunEntity> getCurrentAllSysRuns(String menuElId, SysUserEntity userEntity) {
        //查询当前用户权限
        if (userEntity.getSuperAdmin() == 1) {
            List<Integer> roleIdList = userEntity.getRoles();
            if (CollectionUtils.isEmpty(roleIdList)) {
                roleIdList = InstanceUtil.newArrayList(1);
            }
            //对于超级管理员，加上审核者角色
            roleIdList.add(SystemProperties.Constants.AUDITOR_IDS[0]);
            userEntity.setRoles(roleIdList);
        }
        List<SysRunEntity> sysRuns = sysAuthorizeService.getMenuTools(menuElId, userEntity.getRoles());
        return sysRuns;
    }

    /**
     * 获取要保留的按钮权限
     *
     * @param model
     * @param userEntity
     * @param taskInfo
     * @return
     */
    private List<SysRunEntity> getRetainSysRunsForPanelButton(ButtonManageModel model, SysUserEntity userEntity, AuditTaskInfoEntity taskInfo) {
        List<SysRunEntity> retainButtons = new ArrayList<>();
        // 按状态设置按钮组
        if (ResourceStatusEnums.OFF_LINE.getStatus() == model.getStatus()) {
            //下架
            handleOffShelves(retainButtons);
        } else if (ResourceStatusEnums.ON_LINE.getStatus() == (model.getStatus()) ||
                ResourceStatusEnums.CAN_USE.getStatus() == (model.getStatus()) ||
                ResourceStatusEnums.AUDITED_NOT_ON_LINE.getStatus() == model.getStatus()) {
            //上架、审核通过
            handleAuditedPassAndPutShelves(retainButtons);
        } else if (ResourceStatusEnums.DRAFT.getStatus() == model.getStatus() ||
                ResourceStatusEnums.AUDITED_NOT_PASS.getStatus() == model.getStatus()) {
            //草稿、审核不通过
            handleDraftAndNotPassAudited(retainButtons);
        } else if (ResourceStatusEnums.TO_AUDITING.getStatus() == model.getStatus()) {
            //待审核
            if (isAuditor(userEntity.getRoles()) || userEntity.getSuperAdmin() == 1) {
                SysRunEntity sysRunEntity = new SysRunEntity();
                sysRunEntity.setId(ButtonAccessEnums.AUDIT.getId());
                retainButtons.add(sysRunEntity);
            }
            if (isTaskCreator(userEntity.getId(), taskInfo)) {
                //任务发起人才能操作撤销审核
                SysRunEntity sysRunEntity = new SysRunEntity();
                sysRunEntity.setId(ButtonAccessEnums.UNAUDIT.getId());
                retainButtons.add(sysRunEntity);
            }
        }
        // 合成海报按钮
        addPanelPosterMergeBtn(retainButtons, model);
        return retainButtons;
    }

    /**
     * 合成海报按钮
     *
     * @param retainButtons
     * @param model
     */
    private void addPanelPosterMergeBtn(List<SysRunEntity> retainButtons, ButtonManageModel model) {
        if (MenuTokenConstants.PANEL_INFO.equals(model.getMenuElId())) {
            if (ResourceStatusValidator.isCanAddPosterMergeBtn(model.getStatus())) {
                PanelInfoEntity panelInfoEntity = panelInfoBiz.queryById(model.getResourceId());
                if (null != panelInfoEntity && PanelTypeConstants.isCanMergePoster(panelInfoEntity.getPanelType())) {
                    retainButtons.add(new SysRunEntity(ButtonAccessEnums.REFRESH_PANEL_POSTER_MERGE.getId()));
                }
            }
        }
    }

    private boolean isTaskCreator(Integer userId, AuditTaskInfoEntity taskInfo) {
        return taskInfo != null && userId.equals(taskInfo.getCreator());
    }

    /**
     * 处理下架
     *
     * @param retainButtons
     */
    private void handleOffShelves(List<SysRunEntity> retainButtons) {
        retainButtons.add(new SysRunEntity(ButtonAccessEnums.SHELVES.getId()));
        retainButtons.add(new SysRunEntity(ButtonAccessEnums.COPY.getId()));
    }

    /**
     * 处理审核通过 和 上架
     *
     * @param retainButtons
     */
    private void handleAuditedPassAndPutShelves(List<SysRunEntity> retainButtons) {
        retainButtons.add(new SysRunEntity(ButtonAccessEnums.COPY.getId()));
    }

    /**
     * 处理草稿和审核不通过
     *
     * @param retainButtons
     */
    private void handleDraftAndNotPassAudited(List<SysRunEntity> retainButtons) {
        retainButtons.add(new SysRunEntity(ButtonAccessEnums.EDIT.getId()));
        retainButtons.add(new SysRunEntity(ButtonAccessEnums.DELETE.getId()));
    }

    /**
     * 判断是否审核者
     *
     * @param roleIds
     * @return
     */
    private boolean isAuditor(List<Integer> roleIds) {
        try {
            for (String auditorId : systemProperties.getAuditorIds().split(",")) {
                if (roleIds.contains(Integer.parseInt(auditorId))) {
                    return true;
                }
            }
        } catch (NumberFormatException e) {
            Map errMap = InstanceUtil.newHashMap("auditorIds", systemProperties.getAuditorIds().split(","));
            errMap.put("roleIds", JsonUtil.obj2Json(roleIds));
            throw new BusinessException(errMap, "Button the permission service to determine if the reviewer is abnormal！");
        }
        return false;
    }
}
